package org.apache.ibatis.demo;

import org.apache.ibatis.demo.entity.Blog;
import org.apache.ibatis.demo.mapper.BlogMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

/**
 * @fileName: TestDemo
 * @author: zengqf3
 * @date: 2021-3-9 11:47
 * @description:
 */
public class TestDemo3 {

  public static void main222(String[] args) throws Exception {
    // 加载mybatis配置文件，并创建SqlSessionFactory实例
    String resource = "mybatis-config2.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //这个build方法可以接受几种不同的参数，如Reader/InputSteam等
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = factory.openSession();
    Blog blog = sqlSession.selectOne("org.apache.ibatis.demo.mapper.BlogMapper.selectBlogById", 1);
    //    //默认不自动提交事务，需要手动提交事务
    sqlSession.commit();
    System.out.println(blog);
  }

  public static void main(String[] args) {
    String resource = "mybatis-config2.xml";
    Reader reader;
    try {
      //将XML配置文件构建为Configuration配置类
      reader = Resources.getResourceAsReader(resource);
      // 通过加载配置文件流构建一个SqlSessionFactory  DefaultSqlSessionFactory
      SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
      // 数据源 执行器  DefaultSqlSession
      SqlSession session = sqlMapper.openSession();
      try {
        // 执行查询 底层执行jdbc
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        System.out.println(mapper.getClass());
        Blog blog = mapper.selectBlogById(1L);
        System.out.println(blog);
      } catch (Exception e) {
        e.printStackTrace();
      }finally {
        session.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main2(String[] args) {
    String resource = "mybatis-config2.xml";
    Reader reader;
    try {
      //将XML配置文件构建为Configuration配置类
      reader = Resources.getResourceAsReader(resource);
      // 通过加载配置文件流构建一个SqlSessionFactory  DefaultSqlSessionFactory
      SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
      // 数据源 执行器  DefaultSqlSession
      SqlSession sqlSession = sessionFactory.openSession();
      try {
        // 执行查询 底层执行jdbc
        Blog blog = sqlSession.selectOne("org.apache.ibatis.demo.mapper.BlogMapper.selectBlogById", 1);
        //默认不自动提交事务，需要手动提交事务
        sqlSession.commit();
        System.out.println(blog);
      } catch (Exception e) {
        e.printStackTrace();
      }finally {
        sqlSession.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}
